package cn.ccew.test;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.sql.DataSource;

public class JdbcUtils {

	private DataSource dataSource;

	private static char[] numbersAndLetters = null;
	private static Random randGen = null;
	private static Object initLock = new Object();

	public Connection getConnection() throws SQLException,
			PropertyVetoException {
		return this.dataSource.getConnection();
	}

	public void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						if (!conn.isClosed())
							conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
		}
	}

	public static String getId() throws SQLException {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		return formatter.format(currentTime) + randomString(6);
	}

	private static String randomString(int length) {
		if (length < 1) {
			return null;
		}
		if (randGen == null) {
			synchronized (initLock) {
				if (randGen == null) {
					randGen = new Random();
					numbersAndLetters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
							.toCharArray();
				}
			}
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(32)];
		}
		return new String(randBuffer);
	}

	public static void main(String[] args) throws SQLException {
		for (int i = 0; i <33; i++) {
			System.out.println(getId());
		}
	}

}